package com.cloudinnov.controller.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloudinnov.aop.SystemLog;
import com.cloudinnov.logic.AlarmWorkOrdersLogic;
import com.cloudinnov.logic.AuthResourcesLogic;
import com.cloudinnov.logic.AuthRoleUserLogic;
import com.cloudinnov.logic.AuthUserLogic;
import com.cloudinnov.logic.CompaniesLogic;
import com.cloudinnov.logic.SysLogsLogic;
import com.cloudinnov.model.AlarmWorkOrders;
import com.cloudinnov.model.AuthResource;
import com.cloudinnov.model.AuthRoleUser;
import com.cloudinnov.model.AuthUsers;
import com.cloudinnov.model.Companies;
import com.cloudinnov.model.SysLogs;
import com.cloudinnov.model.TreeObject;
import com.cloudinnov.utils.CommonUtils;
import com.cloudinnov.utils.HttpUtil;
import com.cloudinnov.utils.PropertiesUtils;
import com.cloudinnov.utils.TokenUtil;
import com.cloudinnov.utils.TreeUtil;
import com.cloudinnov.utils.VerifyCodeUtils;
import com.easemob.server.example.comm.wrapper.ResponseWrapper;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * The type Login controller.
 * @author guochao
 * @date 2016年2月18日上午9 :46:12
 * @email chaoguo @cloudinnov.com
 * @remark 登陆controller
 * @update 2016年2月24日15 :11:27 chengning
 */
@Controller
@RequestMapping
public class LoginController extends BaseController {
	private static final Logger logger = Logger.getLogger(LoginController.class);
	private static final String VERIFIC_LENGTH = "length";
	private static final String DEVICE_ID = "deviceId";
	private static final String VERIFIC_IMAGE = "image";
	@SuppressWarnings("unused")
	private static final String ICODE_TYPE_LOGIN = "login";
	private static final String ICODE_TYPE_RESET = "reset";
	@Autowired
	private AuthUserLogic authUserLogic;
	@Autowired
	private AuthResourcesLogic authResourceLogic;
	@Autowired
	private CompaniesLogic companiesLogic;
	@Autowired
	private AlarmWorkOrdersLogic alarmWorkOrdersLogic;
	@Autowired
	private SysLogsLogic sysLogsLogic;
	@Autowired
	private AuthRoleUserLogic authRoleUserLogic;
	@Autowired
	private JedisPool jedisPool;

	@RequestMapping(value = "/logindo", method = RequestMethod.POST)
	@ResponseBody
	public void login(AuthUsers user, HttpServletRequest request, HttpServletResponse response, HttpSession session)
			throws IOException {
		// 跨域处理
		response.setContentType("text/html;charset=UTF-8");
		response.addHeader("Access-Control-Allow-Origin", "*");
		if ("IE".equals(request.getParameter("type"))) {
			response.addHeader("XDomainRequestAllowed", "1");
		}
		ObjectMapper mapper = new ObjectMapper();
		mapper.setSerializationInclusion(Include.NON_NULL);
		Jedis redisClient = null;
		try {
			redisClient = jedisPool.getResource();
			redisClient.select(CommonUtils.REDIS_LOGIN_VALUEDB);
			String userType = request.getParameter("type");
			if (userType != null) {
				user.setUserType(userType);
			} else {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("code", CommonUtils.PARAMETER_EXCEPTION_CODE);
				map.put("msg", CommonUtils.PARAMETER_EXCEPTION_MSG);
				response.getWriter().println(mapper.writeValueAsString(map));
				return;
			}
			AuthUsers loginUser = authUserLogic.login(user);
			if (null != loginUser) {
				// 生成token
				String token = TokenUtil.getInstance().saveToken();
				// 查询登录用户所属oemCode
				Companies company = new Companies();
				company.setCode(loginUser.getCompanyCode());
				company.setLanguage(loginUser.getDefaultLanguage());
				Companies com = companiesLogic.select(company);
				String oemCode = com.getOemCode();
				String integratorCode = com.getIntegratorCode();
				// 失效时间
				int outOfServiceTime = Integer.valueOf(PropertiesUtils.findPropertiesKey("tokenTimeOut"));
				redisClient.setex("login:" + loginUser.getCode() + ":logo", outOfServiceTime,
						loginUser.getLogo() != null ? loginUser.getLogo() : "");
				redisClient.setex("login:" + token + ":code", outOfServiceTime,
						loginUser.getCode() != null ? loginUser.getCode() : "");
				redisClient.setex("login:" + token + ":loginName", outOfServiceTime,
						loginUser.getLoginName() != null ? loginUser.getLoginName() : "");
				redisClient.setex("login:" + token + ":name", outOfServiceTime,
						loginUser.getName() != null ? loginUser.getName() : "");
				redisClient.setex("login:" + token + ":companyCode", outOfServiceTime,
						loginUser.getCompanyCode() != null ? loginUser.getCompanyCode() : "");
				if (oemCode != null) {
					redisClient.setex("login:" + token + ":oemCode", outOfServiceTime, oemCode);
				}
				if (integratorCode != null) {
					redisClient.setex("login:" + token + ":integratorCode", outOfServiceTime, integratorCode);
				}
				redisClient.setex("login:" + token + ":type", outOfServiceTime,
						com.getType() != null ? com.getType() : "");
				redisClient.setex("login:" + token + ":loginFlag", outOfServiceTime, "success");
				// 记录登录信息
				SysLogs sysLog = new SysLogs();
				sysLog.setLoginName(loginUser.getLoginName());
				sysLog.setMethods("用户登录");
				sysLog.setModule("用户管理");
				sysLog.setOemCode(com.getOemCode());
				sysLog.setUserCode(loginUser.getCode());
				sysLog.setDescription("登录成功");
				sysLogsLogic.saveLoginLog(sysLog, request);
				loginUser.setLanguage(loginUser.getDefaultLanguage());
				// 获取顶级资源
				List<AuthResource> parnetResources = authResourceLogic.selectParentsResource(loginUser);
				// 获取常用资源
				List<AuthResource> commonResources = authResourceLogic.selectCommonsResource(loginUser);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("commonMenus", commonResources);
				map.put("menus", parnetResources);
				AlarmWorkOrders alarm = new AlarmWorkOrders();
				alarm.setPaddingBy(loginUser.getCode());
				alarm.setLanguage(loginUser.getDefaultLanguage());
				/**
				 * 查询我的工单消息
				 */
				List<AlarmWorkOrders> alarmCount = alarmWorkOrdersLogic.selectListWhere(alarm);
				map.put("alarmcount", alarmCount.size());
				map.put("token", token);
				map.put("user", loginUser);
				map.put("msg", loginUser.getDefaultLanguage());
				map.put("code", SUCCESS);
				response.getWriter().println(mapper.writeValueAsString(map));
			} else {
				// 用户名密码验证失败
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("code", LOGIN_ERROR_USER);
				map.put("msg", LOGIN_ERROR_USER_MSG);
				response.getWriter().println(mapper.writeValueAsString(map));
			}
		} catch (Exception e) {
			logger.error("Login Is Bad, \t", e);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("code", CommonUtils.SYSTEM_EXCEPTION_CODE);
			map.put("msg", CommonUtils.SYSTEM_EXCEPTION_MSG);
			response.getWriter().println(mapper.writeValueAsString(map));
		} finally {
			jedisPool.returnResource(redisClient);
		}
	}
	@RequestMapping(value = "/m/logindo", method = RequestMethod.POST)
	@ResponseBody
	public void moblieLogin(AuthUsers user, HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws IOException {
		// 跨域处理
		response.setContentType("text/html;charset=UTF-8");
		response.addHeader("Access-Control-Allow-Origin", "*");
		if ("IE".equals(request.getParameter("type"))) {
			response.addHeader("XDomainRequestAllowed", "1");
		}
		ObjectMapper mapper = new ObjectMapper();
		Jedis redisClient = null;
		try {
			redisClient = jedisPool.getResource();
			redisClient.select(Integer.parseInt(PropertiesUtils.findPropertiesKey("redis.db.login")));
			String userType = request.getParameter("type");
			user.setUserType(userType);
			AuthUsers loginUser = authUserLogic.login(user);
			if (null != loginUser) {
				// 生成token
				String token = TokenUtil.getInstance().saveToken();
				user.setToken(token);
				authUserLogic.androidLoginCheck(user);
				// 查询登录用户所属oemCode
				Companies company = new Companies();
				company.setCode(loginUser.getCompanyCode());
				company.setLanguage(loginUser.getDefaultLanguage());
				Companies com = companiesLogic.select(company);
				// 失效时间
				int outOfServiceTime = Integer.valueOf(PropertiesUtils.findPropertiesKey("tokenTimeOut"));
				redisClient.setex("login:" + loginUser.getCode() + ":logo", outOfServiceTime,
						loginUser.getLogo() != null ? loginUser.getLogo() : "");
				redisClient.setex("login:" + token + ":code", outOfServiceTime,
						loginUser.getCode() != null ? loginUser.getCode() : "");
				redisClient.setex("login:" + token + ":loginName", outOfServiceTime,
						loginUser.getLoginName() != null ? loginUser.getLoginName() : "");
				redisClient.setex("login:" + token + ":name", outOfServiceTime,
						loginUser.getName() != null ? loginUser.getName() : "");
				redisClient.setex("login:" + token + ":companyCode", outOfServiceTime,
						loginUser.getCompanyCode() != null ? loginUser.getCompanyCode() : "");
				redisClient.setex("login:" + token + ":oemCode", outOfServiceTime,
						com.getOemCode() != null ? com.getOemCode() : "");
				redisClient.setex("login:" + token + ":type", outOfServiceTime,
						com.getType() != null ? com.getType() : "");
				redisClient.setex("login:" + token + ":loginFlag", outOfServiceTime, "success");
				redisClient.setex("login:name:" + loginUser.getLoginName() + ":loginFlag", outOfServiceTime, "success");
				// 判断资源中是否包含产线监控，包含产线监控则默认进入产线监控页面
				List<AuthResource> resources = authResourceLogic.selectResourceByUser(loginUser);
				for (AuthResource resource : resources) {
					if (resource.getUrl().indexOf("productionline") != -1) {
						loginUser.setDefaultView(2);
					}
				}
				// 记录登录信息
				SysLogs sysLog = new SysLogs();
				sysLog.setLoginName(loginUser.getLoginName());
				sysLog.setMethods("用户登录");
				sysLog.setModule("用户管理");
				sysLog.setOemCode(com.getOemCode());
				sysLog.setUserCode(loginUser.getCode());
				sysLog.setDescription("APP登录成功");
				sysLogsLogic.saveLoginLog(sysLog, request);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("token", token);
				map.put("user", loginUser);
				map.put("msg", loginUser.getDefaultLanguage());
				map.put("code", SUCCESS);
				response.getWriter().println(mapper.writeValueAsString(map));
			} else {
				// 用户名密码验证失败
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("code", LOGIN_ERROR_USER);
				map.put("msg", LOGIN_ERROR_USER_MSG);
				response.getWriter().println(mapper.writeValueAsString(map));
			}
		} catch (Exception e) {
			logger.error("MoblieLogin Exception \t", e);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("code", CommonUtils.SYSTEM_EXCEPTION_CODE);
			map.put("msg", CommonUtils.SYSTEM_EXCEPTION_MSG);
			response.getWriter().println(mapper.writeValueAsString(map));
		} finally {
			jedisPool.returnResource(redisClient);
		}
	}
	@RequestMapping(value = "/logout", method = RequestMethod.POST)
	@ResponseBody
	public void logout(String logout, HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 跨域处理
		response.setContentType("text/html;charset=UTF-8");
		response.addHeader("Access-Control-Allow-Origin", "*");
		if ("IE".equals(request.getParameter("type"))) {
			response.addHeader("XDomainRequestAllowed", "1");
		}
		Jedis redisClient = null;
		try {
			redisClient = jedisPool.getResource();
			redisClient.select(Integer.parseInt(PropertiesUtils.findPropertiesKey("redis.db.login")));
			// 记录退出信息
			SysLogs sysLog = new SysLogs();
			sysLog.setLoginName(redisClient.get("login:" + logout + ":loginName"));
			sysLog.setMethods("用户退出");
			sysLog.setModule("用户管理");
			sysLog.setOemCode(redisClient.get("login:" + logout + ":oemCode"));
			sysLog.setUserCode(redisClient.get("login:" + logout + ":code"));
			sysLog.setDescription("用户退出");
			sysLogsLogic.saveLoginLog(sysLog, request);
			redisClient.del("login:" + logout + ":code");
			redisClient.del("login:" + logout + ":name");
			redisClient.del("login:" + logout + ":companyCode");
			redisClient.del("login:" + logout + ":oemCode");
			redisClient.del("login:" + logout + ":type");
			redisClient.del("login:" + logout + ":loginFlag");
			redisClient.del("login:name:" + redisClient.get("login:" + logout + ":loginName") + ":loginFlag");
		} catch (Exception e) {
			logger.error("登出异常", e);
		} finally {
			jedisPool.returnResource(redisClient);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
		response.getWriter().println(returnData);
	}
	
	@RequestMapping(value = "/webapi/companyUser/nopagelist")
	public void companyUserNoPageList(HttpServletRequest request, AuthUsers users, HttpServletResponse response)
			throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("comCode", getUserInfo(request).get(COM_CODE));
		map.put("language", users.getLanguage());
		List<AuthUsers> list = authUserLogic.selectCustomerUserList(map);
		map = new HashMap<String, Object>();
		if (list != null) {
			map.put("list", list);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}
	
	@RequestMapping(value = "/webapi/companyUser/list")
	public void companyUserList(int index, int size, HttpServletRequest request, AuthUsers users,
			HttpServletResponse response) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		String userType = getUserInfo(request).get(USER_TYPE);
		String companyCode = getUserInfo(request).get(COM_CODE);
		if (userType.equals(CommonUtils.CUSTORER_TYPE)) {
			users.setCompanyCode(companyCode);
			map.put("type", userType);
		}
		if (userType.equals(CommonUtils.OEM_TYPE)) {
			users.setCompanyCode(request.getParameter("companyCode"));
			map.put("type", request.getParameter("type"));
		}
		if (userType.equals(CommonUtils.ADMIN_TYPE)) {
			users.setCompanyCode(request.getParameter("companyCode"));
			map.put("type", request.getParameter("type"));
		}
		if (userType.equals(CommonUtils.INTEGRATOR_TYPE)) {
			map.put("type", request.getParameter("type"));
		}
		map.put("comCode", users.getCompanyCode());
		map.put("language", users.getLanguage());
		Page<AuthUsers> list = authUserLogic.selectOemUserList(index, size, map);
		map = new HashMap<String, Object>();
		if (list != null) {
			map.put("total", list.getTotal());
			map.put("list", list);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}
	@RequestMapping(value = "/webapi/oemUser/list")
	public void oemUserList(int index, int size, HttpServletRequest request, AuthUsers users,
			HttpServletResponse response) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("language", users.getLanguage());
		if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.OEM_TYPE)) {
			map.put("type", CommonUtils.OEM_TYPE);
			map.put("oemCode", getUserInfo(request).get(OEM_CODE));
		} else if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.AGENT_TYPE)) {
			map.put("type", CommonUtils.AGENT_TYPE);
			map.put("agentCode", getUserInfo(request).get(COM_CODE));
		} else if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.ADMIN_TYPE)) {
			map.put("type", CommonUtils.ADMIN_TYPE);
		}
		Page<AuthUsers> list = authUserLogic.selectOemUserList(index, size, map);
		map = new HashMap<String, Object>();
		if (list != null && list.size() > 0) {
			map.put("total", list.getTotal());
			map.put("list", list);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}
	@RequestMapping(value = "/webapi/user/save", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "用户管理", methods = "用户添加")
	public void save(AuthUsers user, HttpServletRequest request, HttpServletResponse response) throws IOException {
		// String userType = getUserInfo(request).get(USER_TYPE);
		String userType = user.getUserType();
		String companyCode = getUserInfo(request).get(COM_CODE);
		String logo = user.getLogo();
		if (logo != null || logo != "") {
			logo = storeBase64(logo, request);
			user.setLogo(logo);
		}
		if (userType.equals(CommonUtils.OEM_TYPE) || userType.equals(CommonUtils.ADMIN_TYPE)) {
			if (user.getCompanyCode() == null) {
				user.setCompanyCode(getUserInfo(request).get(OEM_CODE));
				user.setOemCode(getUserInfo(request).get(OEM_CODE));
			} else {
				user.setOemCode(getUserInfo(request).get(COM_CODE));
			}
		}
		if (userType.equals(CommonUtils.CUSTORER_TYPE)) {
			user.setCompanyCode(companyCode);
			user.setOemCode(getUserInfo(request).get(OEM_CODE));
		}
		String password = user.getLoginPassword();
		user.setDefaultLanguage(CommonUtils.LOGIN_LANGUAGE);
		int returnCode = authUserLogic.save(user);
		Map<String, Object> map = new HashMap<String, Object>();
		if (returnCode == CommonUtils.SUCCESS_NUM) {
			map.put("model", user);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
			ResponseWrapper rep = CommonUtils.createEmchatUser(user.getLoginName(), password, user.getName());// 同时注册环信账号
			if (rep.getResponseStatus() != 200) {
				logger.error("环信账号注册失败,userName" + user.getLoginName() + "\r\n Response:" + rep.getResponseBody());
			}
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}
	@RequestMapping(value = "/webapi/user/update", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "用户管理", methods = "用户修改")
	public void update(AuthUsers user, HttpServletRequest request, HttpServletResponse response) throws IOException {
		String base64S = user.getLogo();
		if (base64S != null && base64S != "" && base64S != "null") {
			String newImg = storeBase64(base64S, request);
			user.setLogo(newImg);
		}
		int returnCode = authUserLogic.update(user);
		Map<String, Object> map = new HashMap<String, Object>();
		if (returnCode == CommonUtils.SUCCESS_NUM) {
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}
	@RequestMapping(value = "/webapi/user/updateUserInfo", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "用户管理", methods = "用户修改")
	public void updateUserInfo(AuthUsers user, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String base64S = user.getLogo();
		if (base64S != null && base64S != "" && base64S != "null") {
			String newImg = storeBase64(base64S, request);
			user.setLogo(newImg);
		}
		int returnCode = authUserLogic.updateUserInfo(user);
		Map<String, Object> map = new HashMap<String, Object>();
		if (returnCode == CommonUtils.SUCCESS_NUM) {
			AuthUsers model = authUserLogic.select(user);
			map.put("model", model);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}
	@RequestMapping(value = "/webapi/user/updateOtherLanguage", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "用户管理", methods = "用户修改")
	public void updateOtherLanguage(AuthUsers user, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		if (user.getOtherLanguage() != null && user.getOtherLanguage() != "") {
			user.setLanguage(user.getOtherLanguage());
		}
		int returnCode = authUserLogic.updateUserInfo(user);
		Map<String, Object> map = new HashMap<String, Object>();
		if (returnCode == CommonUtils.SUCCESS_NUM) {
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}
	@RequestMapping(value = "/webapi/user/saveOtherLanguage", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "用户管理", methods = "用户修改")
	public void updateLanguage(AuthUsers user, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		if (user.getOtherLanguage() != null && user.getOtherLanguage() != "") {
			user.setLanguage(user.getOtherLanguage());
		}
		int returnCode = authUserLogic.updateLanguage(user);
		Map<String, Object> map = new HashMap<String, Object>();
		if (returnCode == CommonUtils.SUCCESS_NUM) {
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}
	@RequestMapping(value = "/webapi/user/select", method = RequestMethod.GET)
	@ResponseBody
	public void select(AuthUsers user, HttpServletRequest request, HttpServletResponse response) throws IOException {
		if (user.getOtherLanguage() != null && user.getOtherLanguage() != "") {
			user.setLanguage(user.getOtherLanguage());
		}
		AuthUsers model = authUserLogic.select(user);
		Map<String, Object> map = new HashMap<String, Object>();
		if (model != null) {
			map.put("model", model);
			AuthRoleUser aru = new AuthRoleUser();
			aru.setUserCode(model.getCode());
			aru.setCompanyCode(model.getCompanyCode());
			aru.setLanguage(user.getLanguage());
			List<AuthRoleUser> selectedResult = authRoleUserLogic.selectList(aru, false);
			String roleNames = "";
			for (AuthRoleUser role : selectedResult) {
				if (role.getRoleName() != null) {
					if (roleNames == "") {
						roleNames = role.getRoleName();
					} else {
						roleNames += CommonUtils.SPLIT_COMMA + role.getRoleName();
					}
				}
			}
			model.setRoleNames(roleNames);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}
	@RequestMapping(value = "/webapi/user/info")
	@ResponseBody
	public void getUserInfo(AuthUsers user, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		user.setCode(getUserInfo(request).get(USER_CODE));
		AuthUsers model = authUserLogic.select(user);
		Map<String, Object> map = new HashMap<String, Object>();
		if (model != null) {
			map.put("model", model);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}
	@RequestMapping(value = "/webapi/user/delete", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "用户管理", methods = "用户删除")
	public void delete(AuthUsers user, HttpServletRequest request, HttpServletResponse response) throws IOException {
		int returnCode = authUserLogic.delete(user);
		Map<String, Object> map = new HashMap<String, Object>();
		if (returnCode == CommonUtils.SUCCESS_NUM) {
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}
	@RequestMapping(value = "/webapi/user/changePassword", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "用户管理", methods = "修改密码")
	public void changePassword(AuthUsers user, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		// 验证原密码
		int returnCode = authUserLogic.checkLoginPassword(user);
		if (returnCode == CommonUtils.SUCCESS_NUM) {
			returnCode = authUserLogic.changePassword(user);
			AuthUsers oldUser = authUserLogic.select(user);
			CommonUtils.changeEmchatUserPwd(oldUser.getLoginName(), user.getNewPassword());// 修改环信密码
			if (returnCode == CommonUtils.SUCCESS_NUM) {
				String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
				response.getWriter().println(returnData);
			} else {
				String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
				response.getWriter().println(returnData);
			}
		} else {
			String returnData = returnJsonAllRequest(request, response, map, PASSWORD_VERIFY_ERROR, null);
			response.getWriter().println(returnData);
		}
	}
	@RequestMapping(value = "/webapi/user/changePhone", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "用户管理", methods = "用户改绑手机")
	public void changePhone(AuthUsers user, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Jedis redisClient = null;
		try {
			redisClient = jedisPool.getResource();
			redisClient.select(Integer.parseInt(PropertiesUtils.findPropertiesKey("redis.db.login")));
			String verifyCode = redisClient.get("verify:changephone:code:" + user.getDeviceId());// 5分钟失效
			ObjectMapper mapper = new ObjectMapper();
			if (verifyCode == null) {// 判断验证码不区分大小写
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("code", LOGIN_ERROR_VERIFYCODE_TIMEOUT);
				map.put("msg", LOGIN_ERROR_VERIFYCODE_TIMEOUT_MSG);
				response.getWriter().println(mapper.writeValueAsString(map));
				return;
			} else if (!verifyCode.equalsIgnoreCase(user.getVerifyCode())) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("code", LOGIN_ERROR_VERIFYCODE);
				map.put("msg", LOGIN_ERROR_VERIFYCODE_MSG);
				response.getWriter().println(mapper.writeValueAsString(map));
				return;
			}
			int returnCode = authUserLogic.checkLoginNameOrPhone(user);
			if (returnCode == CommonUtils.SUCCESS_NUM) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("code", LOGIN_ERROR_PHONE_EXIST);
				map.put("msg", LOGIN_ERROR_PHONE_EXIST_MSG);
				response.getWriter().println(mapper.writeValueAsString(map));
				return;
			}
			Map<String, Object> map = new HashMap<String, Object>();
			user.setCode(getUserInfo(request).get(USER_CODE));
			returnCode = authUserLogic.update(user);
			if (returnCode == CommonUtils.SUCCESS_NUM) {
				String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
				response.getWriter().println(returnData);
			} else {
				String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
				response.getWriter().println(returnData);
			}
		} catch (Exception e) {
			logger.error("changePhone error\r\n", e);
		} finally {
			jedisPool.returnResource(redisClient);
		}
	}
	@RequestMapping(value = "/webapi/m/user/changePhone", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "用户管理", methods = "用户改绑手机")
	public void moblieChangePhone(AuthUsers user, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		int returnCode = authUserLogic.checkLoginNameOrPhone(user);
		if (returnCode == CommonUtils.SUCCESS_NUM) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("code", LOGIN_ERROR_PHONE_EXIST);
			map.put("msg", LOGIN_ERROR_PHONE_EXIST_MSG);
			response.getWriter().println(mapper.writeValueAsString(map));
			return;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		user.setCode(getUserInfo(request).get(USER_CODE));
		returnCode = authUserLogic.update(user);
		if (returnCode == CommonUtils.SUCCESS_NUM) {
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}
	/**
	 * 检查登录账号或者手机号是否存在
	 * @param user
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/webapi/user/checkout")
	@ResponseBody
	public void checkLoginNameOrPhone(AuthUsers user, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		int returnCode = authUserLogic.checkLoginNameOrPhone(user);
		Map<String, Object> map = new HashMap<String, Object>();
		if (returnCode == SUCCESS) {
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}
	/**
	 * 检查密码是否正确
	 * @param user
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/webapi/user/checkoutpassword")
	@ResponseBody
	public void checkOutPassword(AuthUsers user, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		if (user.getLoginPassword().equals("")) {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
			return;
		}
		user.setCode(getUserInfo(request).get(USER_CODE));
		int returnCode = authUserLogic.checkLoginPassword(user);
		if (returnCode == SUCCESS) {
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}
	/**
	 * 获取验证码 getVerifyCode
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @param icodeType
	 * @param @param request
	 * @param @param response 参数
	 * @return void 返回类型
	 */
	@RequestMapping(value = "/getCode")
	public void getVerifyCode(String icodeType, HttpServletRequest request, HttpServletResponse response) {
		// 跨域处理
		response.setContentType("text/html;charset=UTF-8");
		response.addHeader("Access-Control-Allow-Origin", "*");
		if ("IE".equals(request.getParameter("type"))) {
			response.addHeader("XDomainRequestAllowed", "1");
		}
		// 生成随机字串
		String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
		// 存入会话session
		Jedis redisClient = null;
		try {
			redisClient = jedisPool.getResource();
			redisClient.select(Integer.parseInt(PropertiesUtils.findPropertiesKey("redis.db.login")));
			String deviceId = CommonUtils.getUUID();
			redisClient.setex("verify:code:" + deviceId, 300, verifyCode.toLowerCase());// 1分钟失效
			// 生成图片
			int w = 200, h = 80;
			String image = Base64.encodeBase64String(VerifyCodeUtils.outputImage(w, h, verifyCode));
			Map<String, Object> map = new HashMap<String, Object>();
			if (image != null) {
				map.put(VERIFIC_IMAGE, "data:image/png;base64," + image);
				map.put(VERIFIC_LENGTH, verifyCode.length());
				map.put(DEVICE_ID, deviceId);
				String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
				response.getWriter().println(returnData);
			} else {
				String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
				response.getWriter().println(returnData);
			}
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			jedisPool.returnResource(redisClient);
		}
	}
	/**
	 * 手机获取验证码 getPhoneCode
	 * @param phone
	 * @param request
	 * @param response
	 * @param session
	 * @throws IOException
	 */
	@RequestMapping(value = "/getPhoneCode")
	public void getPhoneVerifyCode(String phone, String type, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		if (phone == null) {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
			return;
		}
		if (phone.indexOf("-") != -1) {
			phone = phone.split("-")[1];
		}
		// 跨域处理
		response.setContentType("text/html;charset=UTF-8");
		response.addHeader("Access-Control-Allow-Origin", "*");
		if ("IE".equals(request.getParameter("type"))) {
			response.addHeader("XDomainRequestAllowed", "1");
		}
		// 生成6位随机数字
		String verifyCode = VerifyCodeUtils.phoneVerifyCode(6);
		Jedis redisClient = null;
		try {
			redisClient = jedisPool.getResource();
			redisClient.select(Integer.parseInt(PropertiesUtils.findPropertiesKey("redis.db.login")));
			// 发送手机验证码
			HttpUtil.sendPhoneVerifyCode(phone, verifyCode);
			String deviceId = CommonUtils.getUUID();
			if (type.equals("changePassword")) {
				redisClient.setex("verify:changepassword:code:" + deviceId, 300, verifyCode.toLowerCase());// 5分钟失效
			} else if (type.equals("changePhone")) {
				redisClient.setex("verify:changephone:code:" + deviceId, 300, verifyCode.toLowerCase());// 5分钟失效
			}
			map.put(DEVICE_ID, deviceId);
			map.put(VERIFIC_LENGTH, verifyCode.length());
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} catch (Exception e) {
			logger.error("getPhoneVerifyCode error\r\n", e);
		} finally {
			jedisPool.returnResource(redisClient);
		}
	}
	@RequestMapping(value = "/webapi/user/checkoutPhoneCode")
	@ResponseBody
	public void checkOutPhoneCode(AuthUsers user, String type, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Jedis redisClient = null;
		try {
			redisClient = jedisPool.getResource();
			redisClient.select(Integer.parseInt(PropertiesUtils.findPropertiesKey("redis.db.login")));
			String verifyCode = null;
			ObjectMapper mapper = new ObjectMapper();
			if (user.getVerifyCode() != null) {
				if (type.equals("changePassword")) {
					verifyCode = redisClient.get("verify:changepassword:code:" + user.getDeviceId());// 5分钟失效
				} else if (type.equals("changePhone")) {
					verifyCode = redisClient.get("verify:changephone:code:" + user.getDeviceId());// 5分钟失效
				}
				if (verifyCode == null) {// 判断验证码不区分大小写
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("code", LOGIN_ERROR_VERIFYCODE_TIMEOUT);
					map.put("msg", LOGIN_ERROR_VERIFYCODE_TIMEOUT_MSG);
					response.getWriter().println(mapper.writeValueAsString(map));
					return;
				} else if (!verifyCode.equalsIgnoreCase(user.getVerifyCode())) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("code", LOGIN_ERROR_VERIFYCODE);
					map.put("msg", LOGIN_ERROR_VERIFYCODE_MSG);
					response.getWriter().println(mapper.writeValueAsString(map));
					return;
				}
				Map<String, Object> map = new HashMap<String, Object>();
				String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
				response.getWriter().println(returnData);
			} else {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("code", CommonUtils.PARAMETER_EXCEPTION_CODE);
				map.put("msg", CommonUtils.PARAMETER_EXCEPTION_MSG);
				response.getWriter().println(mapper.writeValueAsString(map));
				return;
			}
		} catch (Exception e) {
			logger.error("checkOutPhoneCode error\r\n", e);
		} finally {
			jedisPool.returnResource(redisClient);
		}
	}
	@RequestMapping(value = "/checkoutCerifyCode")
	@ResponseBody
	public void checkoutVerifyCode(AuthUsers user, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		// 跨域处理
		response.setContentType("text/html;charset=UTF-8");
		response.addHeader("Access-Control-Allow-Origin", "*");
		if ("IE".equals(request.getParameter("type"))) {
			response.addHeader("XDomainRequestAllowed", "1");
		}
		ObjectMapper mapper = new ObjectMapper();
		mapper.setSerializationInclusion(Include.NON_NULL);
		Map<String, Object> map = new HashMap<String, Object>();
		int returnCode = authUserLogic.checkVerifyCode(ICODE_TYPE_RESET, user);
		if (returnCode == LOGIN_ERROR_VERIFYCODE_TIMEOUT) {// 判断验证码不区分大小写
			map.put("code", LOGIN_ERROR_VERIFYCODE_TIMEOUT);
			map.put("msg", LOGIN_ERROR_VERIFYCODE_TIMEOUT_MSG);
			response.getWriter().println(mapper.writeValueAsString(map));
			return;
		} else if (returnCode == LOGIN_ERROR_VERIFYCODE) {
			map.put("code", LOGIN_ERROR_VERIFYCODE);
			map.put("msg", LOGIN_ERROR_VERIFYCODE_MSG);
			response.getWriter().println(mapper.writeValueAsString(map));
			return;
		}
		returnCode = authUserLogic.checkLoginNameOrPhone(user);
		if (returnCode == CommonUtils.SUCCESS_NUM) {
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
			return;
		} else {
			map.put("code", LOGIN_ERROR_PHONE_NO_EXIST);
			map.put("msg", LOGIN_ERROR_PHONE_NO_EXIST_MSG);
			response.getWriter().println(mapper.writeValueAsString(map));
		}
	}
	@RequestMapping(value = "/resetUser")
	@ResponseBody
	public void resetUser(AuthUsers user, HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 跨域处理
		response.setContentType("text/html;charset=UTF-8");
		response.addHeader("Access-Control-Allow-Origin", "*");
		if ("IE".equals(request.getParameter("type"))) {
			response.addHeader("XDomainRequestAllowed", "1");
		}
		ObjectMapper mapper = new ObjectMapper();
		mapper.setSerializationInclusion(Include.NON_NULL);
		Map<String, Object> map = new HashMap<String, Object>();
		Jedis redisClient = null;
		try {
			redisClient = jedisPool.getResource();
			redisClient.select(Integer.parseInt(PropertiesUtils.findPropertiesKey("redis.db.login")));
			String verifyCode = null;
			if (user.getVerifyCode() != null) {
				verifyCode = redisClient.get("verify:reset:code:" + user.getDeviceId());// 5分钟失效
				if (verifyCode == null) {// 判断验证码不区分大小写
					map.put("code", LOGIN_ERROR_VERIFYCODE_TIMEOUT);
					map.put("msg", LOGIN_ERROR_VERIFYCODE_TIMEOUT_MSG);
					response.getWriter().println(mapper.writeValueAsString(map));
					return;
				} else if (!verifyCode.equalsIgnoreCase(user.getVerifyCode())) {
					map.put("code", LOGIN_ERROR_VERIFYCODE);
					map.put("msg", LOGIN_ERROR_VERIFYCODE_MSG);
					response.getWriter().println(mapper.writeValueAsString(map));
					return;
				}
			} else {
				map.put("code", CommonUtils.PARAMETER_EXCEPTION_CODE);
				map.put("msg", CommonUtils.PARAMETER_EXCEPTION_MSG);
				response.getWriter().println(mapper.writeValueAsString(map));
				return;
			}
			AuthUsers resetUser = authUserLogic.selectAreaAndPhone(user.getPhone());
			if (resetUser != null) {
				// 生成8位密码
				String resetPwd = VerifyCodeUtils.phoneVerifyCode(8);
				// 发送密码到手机
				HttpUtil.sendResetPwdVerify(resetUser.getPhone(), resetPwd);
				CommonUtils.changeEmchatUserPwd(resetUser.getLoginName(), resetPwd);// 修改环信密码
				// 修改用户登录密码
				resetUser.setLoginPassword(resetPwd);
				int returnCode = authUserLogic.resetPassword(resetUser);
				if (returnCode == CommonUtils.SUCCESS_NUM) {
					returnJsonAllRequest(request, response, map, SUCCESS, null);
				} else {
					returnJsonAllRequest(request, response, map, ERROR, null);
				}
			} else {
				map.put("code", LOGIN_ERROR_PHONE_NO_EXIST);
				map.put("msg", LOGIN_ERROR_PHONE_NO_EXIST_MSG);
				response.getWriter().println(mapper.writeValueAsString(map));
			}
		} catch (Exception e) {
			logger.error("checkOutPhoneCode error\r\n", e);
		} finally {
			jedisPool.returnResource(redisClient);
		}
	}
	/**
	 * 检查登录账号或者手机号是否存在
	 * @param user
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/checkoutphone")
	@ResponseBody
	public void checkoutPhone(AuthUsers user, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		// 跨域处理
		response.setContentType("text/html;charset=UTF-8");
		response.addHeader("Access-Control-Allow-Origin", "*");
		if ("IE".equals(request.getParameter("type"))) {
			response.addHeader("XDomainRequestAllowed", "1");
		}
		int returnCode = authUserLogic.checkLoginNameOrPhone(user);
		Map<String, Object> map = new HashMap<String, Object>();
		if (returnCode == SUCCESS) {
			map.put("model", SUCCESS);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			map.put("model", ERROR);
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}
	/**
	 * 获取子菜单
	 * @Title: selectChildrensResource
	 * @Description: TODO
	 * @param user
	 * @param request
	 * @param response
	 * @throws IOException
	 * @return: void
	 */
	@RequestMapping(value = "/webapi/getChildrensResource", method = RequestMethod.GET)
	@ResponseBody
	public void selectChildrensResource(AuthUsers user, Integer parentId, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		user.setCode(getUserInfo(request).get(USER_CODE));
		user.setCustomerCode(getUserInfo(request).get(COM_CODE));
		user.setCompanyCode(getUserInfo(request).get(COM_CODE));
		List<AuthResource> allResources = authResourceLogic.selectResourceByUser(user);
		Iterator<AuthResource> it = allResources.iterator();
		while (it.hasNext()) {
			AuthResource ele = (AuthResource) it.next();
			if (ele.getParentId() == 0 && ele.getParentId() != parentId) {
				it.remove();
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		if (allResources != null && allResources.size() > 0) {
			List<TreeObject> menus = new ArrayList<TreeObject>();
			for (int i = 0; i < allResources.size(); i++) {
				TreeObject ts = new TreeObject();
				if (allResources.get(i) != null) {
					ts.setParentId(allResources.get(i).getParentId());
					ts.setSelectId(allResources.get(i).getSelId());
					ts.setName(allResources.get(i).getName());
					ts.setGrade(allResources.get(i).getGrade());
					ts.setUrl(allResources.get(i).getUrl());
					ts.setIcon(allResources.get(i).getIcon());
					ts.setIsCommon(allResources.get(i).getIsCommon());
					menus.add(ts);
				}
			}
			TreeUtil treeUtil = new TreeUtil();
			List<TreeObject> ns = treeUtil.getChildTreeObjects(menus, parentId);
			map.put("list", ns);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			map.put("list", Collections.emptyList());
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}
}
